import { useMemberStore } from '@/store/member';
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net';

// 请求之前触发
uni.addInterceptor('request', {
  invoke(args) {
    // console.log(args);
    args.url = baseURL + args.url;
    const memberStore = useMemberStore();
    const token = memberStore.profile.token;
    args.header = args.header || {};
    if (token) {
      args.header.Authorization = token;
    }
  },
});
// 修改头像
uni.addInterceptor('uploadFile', {
  invoke(args) {
    // console.log(args);
    args.url = baseURL + args.url;
    const memberStore = useMemberStore();
    const token = memberStore.profile.token;
    args.header = args.header || {};
    if (token) {
      args.header.Authorization = token;
    }
  },
});

type Date<T> = {
  code: string;
  msg: string;
  result: T;
};
// 封装一个请求方法 让请求支持 Promise 风格
const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        // console.log(res);
        if (res.statusCode === 200) {
          resolve((res.data as Date<T>).result);
        } else {
          reject(res);
        }
      },
    });
  });
};

export default http;
